<template>
  <div class="or-show-notice">
    <div class="button-container">
      <div class="filter-buttons">
        <button 
          :class="{ active: filterStatus === 'all' }" 
          @click="filterNotices('all')"
        >
          全部
        </button>
        <button 
          :class="{ active: filterStatus === 'read' }" 
          @click="filterNotices('read')"
        >
          已读
        </button>
        <button 
          :class="{ active: filterStatus === 'unread' }" 
          @click="filterNotices('unread')"
        >
          未读
        </button>
      </div>
      <h2 class="page-title">我收到的通知</h2>
      <div class="action-buttons">
        <button class="received-button" @click="handleReceivedNotices">返回发布通知</button>
      </div>
    </div>
    <div class="notice-list">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="filteredNotices.length === 0" class="no-notices">暂无通知</div>
      <div v-else class="notice-items">
        <div v-for="item in filteredNotices" :key="item.noticeDetail.id" class="notice-item">
          <div class="notice-header">
            <h3>{{ item.noticeDetail.title }}</h3>
            <span class="create-time">{{ formatDate(item.noticeDetail.createTime) }}</span>
          </div>
          <div class="notice-content">
            {{ item.noticeDetail.content }}
          </div>
          <div class="notice-info">
            <span>{{ getReceiverType(item.noticeDetail.receiverType) }}可见</span>
            <span>状态: {{ item.noticeGiven.isRead ? '已读' : '未读' }}</span>
          </div>
          <div class="notice-actions" v-if="!item.noticeGiven.isRead">
            <button class="mark-as-read-btn" @click="markAsRead(item.noticeGiven.id)">
              标记为已读
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'

interface NoticeGiven {
  id: number
  isRead: number
  sendTime: string
  uid: number | null
  nid: number
  oid: number | null
  mid: number | null
}

interface NoticeDetail {
  id: number
  senderType: number
  senderId: number
  receiverType: number
  receiverOneType: number | null
  receiverId: number | null
  title: string
  content: string
  createTime: string
  isUsing: boolean
}

interface NoticeItem {
  noticeGiven: NoticeGiven
  noticeDetail: NoticeDetail
}

const notices = ref<NoticeItem[]>([])
const loading = ref(true)
const filterStatus = ref<'all' | 'read' | 'unread'>('all')

// 获取通知列表
const fetchNotices = async () => {
  try {
    const token = localStorage.getItem('token')
    
    if (!token) {
      alert('未找到有效的身份凭证，请重新登录')
      loading.value = false
      return
    }

    const response = await fetch('http://localhost:8080/ng/list', {
      method: 'GET',
      headers: {
        'token': token
      }
    })

    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        notices.value = result.notices
      } else {
        alert('获取通知失败')
      }
    } else {
      alert('网络请求失败')
    }
  } catch (error) {
    console.error('获取通知时出错:', error)
    alert('获取通知时发生错误')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取发送者类型
const getSenderType = (type: number) => {
  switch (type) {
    case 0: return '系统'
    case 1: return '主办方'
    case 2: return '管理员'
    default: return '未知'
  }
}

// 获取接收者类型
const getReceiverType = (type: number) => {
  switch (type) {
    case 0: return '单独发送'
    case 1: return '所有人'
    case 2: return '管理员'
    case 3: return '主办方'
    case 4: return '用户'
    case 5: return '非管理员'
    case 6: return '非主办方'
    case 7: return '非用户'
    default: return '未知'
  }
}

// 筛选通知
const filteredNotices = computed(() => {
  if (filterStatus.value === 'all') {
    return notices.value
  } else if (filterStatus.value === 'read') {
    return notices.value.filter(item => item.noticeGiven.isRead === 1)
  } else {
    return notices.value.filter(item => item.noticeGiven.isRead === 0)
  }
})

const filterNotices = (status: 'all' | 'read' | 'unread') => {
  filterStatus.value = status
}

const handleNewNotice = () => {
  // 触发跳转到新建通知页面的事件
  window.dispatchEvent(new CustomEvent('showNewNotice'))
}

const handleReceivedNotices = () => {
  // 触发跳转到我发布的通知页面的事件
  window.dispatchEvent(new CustomEvent('showNoticeList'))
}

// 添加标记为已读的方法
const markAsRead = async (id: number) => {
  try {
    const token = localStorage.getItem('token')
    
    if (!token) {
      alert('未找到有效的身份凭证，请重新登录')
      return
    }

    const response = await fetch(`http://localhost:8080/ng/markAsRead?id=${id}`, {
      method: 'PUT',
      headers: {
        'token': token
      }
    })

    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        // 更新本地状态
        const notice = notices.value.find(item => item.noticeGiven.id === id)
        if (notice) {
          notice.noticeGiven.isRead = 1
        }
        alert('标记为已读成功')
      } else {
        alert('标记失败: ' + (result.message || '未知错误'))
      }
    } else {
      alert('网络请求失败')
    }
  } catch (error) {
    console.error('标记为已读时出错:', error)
    alert('标记为已读时发生错误')
  }
}

// 添加事件监听器
// 在组件挂载时获取通知
onMounted(() => {
  fetchNotices()
})

onUnmounted(() => {
  // 移除组件相关的事件监听器（如果有的话）
})
</script>

<style scoped>
.or-show-notice {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.page-title {
  font-size: 32px;
  color: #2E7D32;
  text-shadow: 0 0 8px rgba(56, 142, 60, 0.5);
  font-family: '微软雅黑', sans-serif;
  font-weight: bold;
  text-align: center;
  flex: 1;
}

.button-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.filter-buttons button {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-buttons button.active,
.filter-buttons button:hover {
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border-color: #43A047;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.new-button {
  padding: 10px 20px;
  background: linear-gradient(to right, #66BB6A, #43A047);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  font-family: '微软雅黑 Light', sans-serif;
}

.new-button:hover {
  background: linear-gradient(to right, #558B2F, #388E3C);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.received-button {
  padding: 10px 20px;
  background: linear-gradient(to right, #4FC3F7, #29B6F6);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  font-family: '微软雅黑 Light', sans-serif;
}

.received-button:hover {
  background: linear-gradient(to right, #29B6F6, #039BE5);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.mark-as-read-btn {
  padding: 8px 16px;
  background: linear-gradient(to right, #FFB74D, #FFA726);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  font-family: '微软雅黑 Light', sans-serif;
}

.mark-as-read-btn:hover {
  background: linear-gradient(to right, #FFA726, #FB8C00);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.notice-list {
  background: none;
  border: none;
  border-radius: 0;
  padding: 0;
  min-height: 300px;
  box-shadow: none;
}

.loading, .no-notices {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 18px;
}

.notice-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.notice-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  background-color: #f9f9f9;
}

.notice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.notice-header h3 {
  margin: 0;
  color: #388E3C;
  font-size: 18px;
  font-weight: bold;
}

.create-time {
  font-size: 16px;
  color: #888;
}

.notice-content {
  margin-bottom: 10px;
  line-height: 1.5;
  font-size: 16px;
}

.notice-info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.notice-info span {
  font-size: 16px;
}

.notice-sender {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-size: 14px;
  color: #666;
  text-align: right;
}
</style>